﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using Home.Site.Models;
using Home.Site.Models.Account;
using Home.Site.Models.DataLayer;

namespace Home.Site.Controllers
{
    public class OfferController : Controller
    {
        private readonly IOfferRepository offerRepository;
        private readonly IAccountRepository accountRepository;

        public OfferController(IOfferRepository offerRepository, IAccountRepository accountRepository)
        {
            this.offerRepository = offerRepository;
            this.accountRepository = accountRepository;
        }


        [Authorize]
        public ActionResult Index(IPrincipal currentUser)
        {
            var user = accountRepository.GetUser(currentUser);
            if (!user.IsAdmin)
            {
                return View("Error");
            }
            var model = offerRepository.All;
            return View("Offer/Index",model);
        }

        public ActionResult All(IPrincipal currentUser)
        {
            var model = offerRepository.All.OrderByDescending(o=>o.idoffer);
            return View("All", model);
        }

        public ActionResult Create()
        {
            return View("Offer/CreateOffer");
        }

        [HttpPost]
        public ActionResult Create(string description, string title)
        {
            if (String.IsNullOrEmpty(title) && description.Length > 5)
            {
                if (ModelState.IsValid)
                {
                    var offer = new Offer
                    {
                        dateOffer = DateTime.Now.Date,
                        ip = HttpContext.Request.UserHostAddress,
                        title = description.Substring(0, description.Length > 10 ? 10 : description.Length),
                        description = description
                    };

                    offerRepository.InsertOrUpdate(offer);
                    offerRepository.Save();
                    return RedirectToAction("All","Offer");
                }
            }
            return RedirectToAction("All", "Offer",new {Error = "Длина пожелания должна быть более пяти символов!"});
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, IPrincipal currentUser)
        {
            var user = accountRepository.GetUser(currentUser);
            if (!user.IsAdmin)
            {
                return View("Error");
            }
            offerRepository.Delete(id);
            offerRepository.Save();

            return RedirectToAction("All");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                offerRepository.Dispose();
            }
            base.Dispose(disposing);
        }

    }
}
